package tgc.edu.ljc.layui.web.controller;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.ljc.layui.custom.DataGridParam;
import tgc.edu.ljc.layui.custom.DataGridUtils;
import tgc.edu.ljc.layui.custom.LayUiResult;
import tgc.edu.ljc.layui.entity.Course;
import tgc.edu.ljc.layui.service.CourseService;
import tgc.edu.ljc.layui.web.form.CourseForm;

@Controller
@RequestMapping(value="/course")
public class CourseController {
	@Autowired
	private CourseService service;
	
	@RequestMapping(value="/manage")
	public String manage() {
		return "course/manage";
	}
	
	@RequestMapping(value="/page")
	@ResponseBody
	public Object page(DataGridParam param) {
		Pageable pabeable = param.getPabeable();
		Page<Course> page = service.findAll(pabeable);
		return DataGridUtils.buildResult(page);
	}
	
	@RequestMapping(value="/edit")
	public String edit(Integer id,ModelMap map) {
		Course model=new Course();
		if(id!=null) {
			model=service.findById(id);
		}
		map.put("model", model);
		return "course/edit";
	}
	
	@RequestMapping(value="/save")
	@ResponseBody
	public Object save(CourseForm form) {
		Course model=new Course();
		if(form.getId()!=null) {
			model=service.findById(form.getId());
		}
		BeanUtils.copyProperties(form, model,"id");
		try {
			service.save(model);
			return LayUiResult.getResult();
		}catch (Exception e) {
			return LayUiResult.getErrorResult("数据保存失败！");
		}
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public Object delete(Integer id) {
		try {
			service.deleteById(id);
			return LayUiResult.getResult();
		}catch (Exception e) {
			return LayUiResult.getErrorResult("数据删除失败！");
		}
	}
	
}
